package com.sandking.tools;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @UserName : SandKing
 * @DataTime : 2014年4月4日 上午11:20:09
 * @Description ：索引关系Map
 */
public class SK_IndexMap<K, V> {
	private Map<K, V> keyMap;
	private Map<V, Set<K>> valueMap;

	public SK_IndexMap() {
		super();
		this.keyMap = new ConcurrentHashMap<K, V>();
		this.valueMap = new ConcurrentHashMap<V, Set<K>>();
	}

	public SK_IndexMap(Map<K, V> keyMap, Map<V, Set<K>> valueMap) {
		super();
		this.keyMap = keyMap;
		this.valueMap = valueMap;
	}

	public void put(K key, V value) {
		keyMap.put(key, value);
		Set<K> keys = valueMap.get(value);
		if (keys == null) {
			keys = new HashSet<K>();
		}
		keys.add(key);
		valueMap.put(value, keys);
	}

	public V getValseByKey(String key) {
		return keyMap.get(key);
	}

	public Set<K> getKeysByValuse(V v) {
		return valueMap.get(v);
	}

	public V removeByKey(K key) {
		V v = keyMap.remove(key);
		Set<K> keys = valueMap.get(v);
		if (keys != null && !keys.isEmpty()) {
			keys.remove(key);
		}
		return v;
	}

	public Set<K> removeByValue(V v) {
		Set<K> keys = valueMap.remove(v);
		for (K k : keys) {
			keyMap.remove(k);
		}
		return keys;
	}
}
